package com.zb.framework.config;

import com.alibaba.nacos.api.exception.NacosException;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

/**
 * @author fujianjian
 * @date 2023/3/1 11:35
 **/
@RequiredArgsConstructor
public class ZeusNacosReactorDiscoveryClient implements ReactiveDiscoveryClient {

    private final ZeusNacosServiceDiscovery zeusNacosServiceDiscovery;

    @Override
    public String description() {
        return "Zeus Nacos Reactive Discovery Client";
    }

    @Override
    public Flux<ServiceInstance> getInstances(String serviceId) {
        return Mono.justOrEmpty(serviceId).flatMapMany(sid->{
            try {
                return Flux.fromIterable(zeusNacosServiceDiscovery.getInstances(sid));
            } catch (NacosException nacosException) {
                return Flux.empty();
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }

    @Override
    public Flux<String> getServices() {
        return Flux.defer(()->{
            try {
                return Flux.fromIterable(zeusNacosServiceDiscovery.getServices());
            } catch (NacosException nacosException) {
                return Flux.empty();
            }
        }).subscribeOn(Schedulers.boundedElastic());
    }
}
